'use strict'
/**
部门管理
*/
let urljoin = require("url-join"),
	_ = require("lodash"),
	template = require("es6-template-strings"),
	log4js = require('log4js'),
	logger = log4js.getLogger('qywx-api'),
	debug = require('debug')('qywx-api'),
	rp = require("request-promise"),
	URLs = require('./urls.js').URLs();

module.exports = function() {

	return {
		/**删除部门
		 Params{
		 	accessToken：必须
		 	id :必须
		 }
		 */
		deleteDepartment: function(accessToken, id,cb) {
			let targetUrl =
				template(URLs.CONTACTS_DEPARTMENT_DELETE, {
					accessToken: accessToken
				});

			debug("删除部门: ", targetUrl);
			let requestData = {
				id: id,
			};
			var rpOptions = {
				uri: targetUrl,
				method: "GET",
				qs: requestData,
				json: true
			};
			/**
			 * {
				"errcode": 0,
				"errmsg": "deleted"
				}
			 */
			rp(rpOptions).then(function(data) {
					if (data.errcode > 0) {
						logger.error("request error: ", data);
						return cb(new Error(data.errmsg));
					}
					return cb(null);
				})
				.catch(function(err) {
					logger.error("request error: ", err);
					return cb(err);
				});

		},
		/**修改部门
		 Params{
		 	accessToken：必须
		 	id :必须
			name :否
		 	parentId:否
		 	order：必须
		 	cb:必须
		 }
		备注：请求包结构体为（如果非必须的字段未指定，则不更新该字段之前的设置值）:
		 */
		updateDepartment: function(accessToken, id, name, parentId, order, cb) {
				let targetUrl =
					template(URLs.CONTACTS_DEPARTMENT_UPDATE, {
						accessToken: accessToken
					});

				debug("更新部门信息: ", targetUrl);

				let requestData = {
					id: id,
					name: name,
					parentid: parentId || 1,
					order: order
				};

				var rpOptions = {
					uri: targetUrl,
					method: "post",
					json: true,
					body:requestData
				};
				/**
		      success:
		      {
		        "id": 2,
		        "name": "广州研发中心",
		        "parentid": "1",
		        "order": "1"
		     }
		     error:
		      {
		         "errcode": 0,
		         "errmsg": "updated"
		      }
      */
				rp(rpOptions).then(function(data) {

						if (data.errcode > 0) {
							logger.error("request error: ", data);
							return cb(new Error(data.errmsg));
						}

						return cb(null, requestData);
					})
					.catch(function(err) {
						logger.error("request error: ", err);
						//For lock - if we failed to request new token then we must Unlock it
						//client.lockedForQuery = false;
						return cb(err);
					});

			}
			/**
			 * 添加部门
			 {
			   "name": "广州研发中心", //部门名称。长度限制为1~64个字节，字符不能包括\:*?"<>｜
			   "parentid": "1", //父亲部门id。根部门id为1
			   "order": "1", //在父部门中的次序值。order值小的排序靠前。
			   "id": "1"  //部门id，整型。指定时必须大于1，不指定时则自动生成
			 }
			 */
			,
		createDepartment: function(accessToken, name, parentId, order, id, cb) {
				let targetUrl =
					template(URLs.CONTACTS_DEPARTMENT_CREATE, {
						accessToken: accessToken
					});

				debug("创建部门信息: ", targetUrl);

				let requestData = {
					name: name,
					parentid: parentId,
					order: order
				};

				if (_.isInteger(id) && id > 1) {
					requestData.id = id;
				}

				var rpOptions = {
					uri: targetUrl,
					method: "POST",
					json: true,
					body:requestData
				};

				rp(rpOptions).then(function(data) {
						/**
						    Parse response data
						    {
						       "errcode": 0,
						       "errmsg": "created",
						       "id": 2
						    }
						*/
						if (data.errcode > 0) {
							logger.error("request error: ", data);
							return cb(new Error(data.errmsg));
						}

						requestData.id = data.id;
						return cb(null, requestData);
					})
					.catch(function(err) {
						logger.error("request error: ", err);
						//For lock - if we failed to request new token then we must Unlock it
						//client.lockedForQuery = false;
						return cb(err);
					});


			}
			//
      ,getDepartmentList: function(accessToken, departmentId, cb){
        let targetUrl =
              template(URLs.CONTACTS_DEPARTMENT_LIST,
                  { accessToken: accessToken, departmentId: departmentId });

        debug("获取部门列表: ", targetUrl);

        var rpOptions = {
            uri: targetUrl,
            qs: {//Query parameters
                //access_token: 'xxxxx xxxxx' -> uri + '?access_token=xxxxx%20xxxxx'
            },
            headers: {
                //'User-Agent': 'Request-Promise'
            },
            json: true // Automatically parses the JSON string in the response
        };

        rp(rpOptions).then(function(data){
          /**
              Parse response data
              {
                 "errcode": 0,
                 "errmsg": "ok",
                 "department": [
                     {
                         "id": 2,
                         "name": "广州研发中心",
                         "parentid": 1,
                         "order": 10
                     },
                     {
                         "id": 3
                         "name": "邮箱产品部",
                         "parentid": 2,
                         "order": 40
                     }
                 ]
              }
          */
          if(data.errcode > 0){
            logger.error("request error: ", data);
            return cb(new Error(data.errmsg));
          }
          return cb(null, data.department);
        })
        .catch(function(err){
          logger.error("request error: ", err);
          //For lock - if we failed to request new token then we must Unlock it
          //client.lockedForQuery = false;
          return cb(err);
        });


      }
	}
}
